﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SPFarmModeler.Business;
using SPFarmModeler.Common;

namespace SPFarmModeler.Forms
{
    public partial class MainForm : Form
    {
        // objet cFarm pour current Farm. Il est utilisé pendant tout le temps ou l'application fonctione
        public delegate void FarmChangedEventHandler(object sender, Farm f);
        public event FarmChangedEventHandler FarmChanged;
        private void NotifyFarmChanged(Farm f)
        {
            FarmChanged(this, f);
        }
        private Farm _cFarm = null;          
        public Farm cFarm
        {
            get
            { 
                return _cFarm;  
            }
            set
            {
                _cFarm = value;
                NotifyFarmChanged(_cFarm);
            }
        }

        private string FileName = null;     // FileName property permet de garder le nom complet du fichier stockant la config de la ferme ouverte

        public MainForm()
        {
            InitializeComponent();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (cFarm != null)
            {
                closetoolStripMenuItem_Click(sender, e);
                cFarm = null;
            }
            cFarm = new Farm();             // Création d'un objet de travail cFarm
            groupBox1.Enabled = true;       // et ouverture des champs du formulaire Farm à la saisie
            groupBox2.Enabled = true;
            toolStripStatusLabel_CurrentFarmFile.Text = SPFarmModelerRes.StatusWorkNewFarm;
            SetFarmBindingtoMainForm();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (cFarm != null)
            {
                closetoolStripMenuItem_Click(sender, e);
            }
            
            try
            {
                // Ouverture du sélecteur de fichiers
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                dlg.RestoreDirectory = true;
                dlg.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
                dlg.FilterIndex = 1;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    cFarm = Farm.Open(dlg.FileName);
                    FileName = dlg.FileName;
                    toolStripStatusLabel_CurrentFarmFile.Text = SPFarmModelerRes.StatusCurFarmFileUsed + @"""" + FileName + @"""";
                    groupBox1.Enabled = true;
                    groupBox2.Enabled = true;
                    SetFarmBindingtoMainForm();
                    textBox_Farm_LastSaved.Text = string.Format("{0:g}", cFarm.LastSave);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void closetoolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(SPFarmModelerRes.MsgWantToSave, SPFarmModelerRes.MsgHeaderSave, MessageBoxButtons.YesNo).Equals(DialogResult.Yes))
            {
                saveToolStripMenuItem_Click(sender, e);
            }
            initMainForm();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (cFarm == null)
            {
                MessageBox.Show(SPFarmModelerRes.MsgCreateBeforeSave);
                return;
            }
            if (FileName == null)
                saveFarmAsToolStripMenuItem_Click(sender, e);
            else cFarm.Save(FileName);
            textBox_Farm_LastSaved.Text = string.Format("{0:g}", cFarm.LastSave);
        }

        private void saveFarmAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // Ouverture du sélecteur de fichiers
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                dlg.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
                dlg.FilterIndex = 1;
                dlg.FileName = cFarm.Name + ".xml";    // mieux avec stringBuilder()

                if (dlg.ShowDialog() == DialogResult.OK)
                    cFarm.Save(dlg.FileName);

                FileName = dlg.FileName;
                textBox_Farm_LastSaved.Text = string.Format("{0:g}", cFarm.LastSave);
                toolStripStatusLabel_CurrentFarmFile.Text = SPFarmModelerRes.StatusCurFarmFileUsed + @"""" + FileName + @"""";
            }
            catch (Exception ex)
            {
                Utilities.WriteError("MainForm.saveAsToolStripMenuItem_Click", ex.Message);
                MessageBox.Show(SPFarmModelerRes.MsgUnableToSaveFarmConf);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutFarmModeler About = new AboutFarmModeler();
            About.ShowDialog();
        }

        public void initMainForm()
        {
            cFarm = null;
            groupBox1.Enabled = false;
            groupBox2.Enabled = false;
            foreach (Control ctrl in groupBox1.Controls)
            {
                if (ctrl is TextBox)
                    ctrl.Text = string.Empty;
            }
            foreach (Control ctrl in groupBox2.Controls)
            {
                if (ctrl is TextBox)
                    ctrl.Text = string.Empty;
            }
            ClearFarmBindingtoMainForm();
            toolStripStatusLabel_CurrentFarmFile.Text = SPFarmModelerRes.StatusNoFileUsed;
        }

        private void SetFarmBindingtoMainForm()
        {
            if (cFarm != null)
            {
                // Binding des TextBox
                textBox_Farm_Name.DataBindings.Add("Text", cFarm, "Name");
                textBox_Farm_Desc.DataBindings.Add("Text", cFarm, "Description");
                textBox_Farm_DomainNB.DataBindings.Add("Text", cFarm, "DomainNB");
                textBox_Farm_DomainDNS.DataBindings.Add("Text", cFarm, "DomainDNS");
                textBox_Farm_CentralAdminTCPPort.DataBindings.Add("Text", cFarm, "CentralAdminPort".ToString());
                textBox_Farm_SQLserver.DataBindings.Add("Text", cFarm, "SQLConfigDbServer");
                textBox_Farm_SQLConfigDBname.DataBindings.Add("Text", cFarm, "CentralAdminConfigDbName");
                textBox_Farm_SQLCAcontentDB.DataBindings.Add("Text", cFarm, "CentralAdminContentDbName");

                // Binding des ComboBox
                int val = (int)cFarm.Authentication;
                comboBox_Farm_Authent.DataSource = Utilities.GetCollectionFromEnum<FarmAuthentication>();
                comboBox_Farm_Authent.SelectedIndex = val;

                val = (int)cFarm.Archi;
                comboBox_Farm_ArchiServers.DataSource = Utilities.GetCollectionFromEnum<ServArch>();
                comboBox_Farm_ArchiServers.SelectedIndex = val;

                val = (int)cFarm.Os;
                comboBox_Farm_OSfamily.DataSource = Utilities.GetCollectionFromEnum<ServOS>();
                comboBox_Farm_OSfamily.SelectedIndex = val;

                val = (int)cFarm.Ed;
                comboBox_Farm_OSEdition.DataSource = Utilities.GetCollectionFromEnum<ServED>();
                comboBox_Farm_OSEdition.SelectedIndex = val;

                val = (int)cFarm.Sp;
                comboBox_Farm_OSSP.DataSource = Utilities.GetCollectionFromEnum<ServSP>();
                comboBox_Farm_OSSP.SelectedIndex = val;
              
            }
        }

        private void ClearFarmBindingtoMainForm()
        {
            // Libération des TextBox
            textBox_Farm_Name.DataBindings.Clear();
            textBox_Farm_Desc.DataBindings.Clear();
            textBox_Farm_DomainNB.DataBindings.Clear();
            textBox_Farm_DomainDNS.DataBindings.Clear();
            textBox_Farm_CentralAdminTCPPort.DataBindings.Clear();
            textBox_Farm_SQLserver.DataBindings.Clear();
            textBox_Farm_SQLConfigDBname.DataBindings.Clear();
            textBox_Farm_SQLCAcontentDB.DataBindings.Clear();

            // Libération des ComboBox
            comboBox_Farm_Authent.DataSource = null;
            comboBox_Farm_ArchiServers.DataSource = null;
            comboBox_Farm_OSfamily.DataSource = null;
            comboBox_Farm_OSEdition.DataSource = null;
            comboBox_Farm_OSSP.DataSource = null;
        }

        private void comboBox_Farm_Authent_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cFarm != null)
            {
                int index = comboBox_Farm_Authent.SelectedIndex;
                cFarm.Authentication = (FarmAuthentication)index;
            }
        }

        private void comboBox_Farm_ArchiServers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cFarm != null)
            {
                int index = comboBox_Farm_ArchiServers.SelectedIndex;
                cFarm.Archi = (ServArch)index;
            }

        }

        private void comboBox_Farm_OSfamily_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cFarm != null)
            {
                int index = comboBox_Farm_OSfamily.SelectedIndex;
                cFarm.Os = (ServOS)index;
            }
        }

        private void comboBox_Farm_OSSP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cFarm != null)
            {
                int index = comboBox_Farm_OSSP.SelectedIndex;
                cFarm.Sp = (ServSP)index;
            }
        }

        private void comboBox_Farm_OSEdition_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cFarm != null)
            {
                int index = comboBox_Farm_OSEdition.SelectedIndex;
                cFarm.Ed = (ServED)index;
            }
        }

        private void Servers_Add_button_Click(object sender, EventArgs e)
        {
            AddServerNameForm box = new AddServerNameForm();
            box.ShowDialog();
            servicesAndServersGrid1.AddServer(box.ServerName);
        }
    }

}
